// 导入 http 模块
import http from 'wechat-http'
/**
 * 接口基础路径
 */
http.baseURL = 'https://live-api.itheima.net'
/**
 * 配置请求拦截器
 */
http.intercept.request = (params) => {
  // 过滤接口返回的数据
  const app = getApp()
  if (app.token) {
    params.header = {
      // 把原来的header的数据传回来

      Authorization: `Bearer ${app.token}`,
      ...params.header,
    }
  }
  return params
}
/**
 * 配置响应拦截器
 */
http.intercept.response = async (res) => {
  if (res.statusCode === 401) {
    // refreshToken 过期的情形
    if (res.config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const lastPage = pageStack[pageStack.length - 1]
      const redirectURL = lastPage.route
      return wx.redirectTo({
        url: '/pages/login/index?redirector=' + redirectURL
      })
    }
    // 重新发送请求，获取新的token
    const app = getApp()
    const result = await http({
      url: "/refreshToken",
      method: 'post',
      header: {
        Authorization: 'Bearer ' + app.refreshToken,
      }
    })
    const { token, refreshToken } = result.data
    app.setToken(token, refreshToken)
    // 重新再一次之前的请求
    return await http({
      ...res.config,
      header: {
        Authorization: 'Bearer ' + token,
      }
    })
  }
  console.log(res);
  // 过滤接口返回的数据
  return res.data
}

/**
 * 挂载到wx全局对象
 */
wx.http = http
